﻿Option Explicit On
Imports Microsoft.VisualBasic
Imports System
Imports System.Globalization

Partial Public Class User_Popup
    Inherits System.Web.UI.Page
    Dim clsGet As New ClassFunctionGetData

    Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
        If Not IsPostBack Then
            clsGet.byddlfromDataSet(ddlRole, clsGet.LoadRole(), "Role_name", "Role_no")
            'Dim lbUser As Label = CType(Master.FindControl("lbMenu"), Label)
            'lbUser.Text = "USER"
            If (Session("EditMaster") Is Nothing) Then
                btnSave.Visible = False
            End If

            If Not (Session("User_IPORT") Is Nothing) Then
                txtUsername.Text = Session("User_IPORT").ToString().Split("$")(0)
                txtUsername.Enabled = False
                txtName.Text = Session("User_IPORT").ToString().Split("$")(1)
                txtEmail.Text = Session("User_IPORT").ToString().Split("$")(2)
                If Not (ddlStatus.Items.FindByValue(Session("User_IPORT").ToString().Split("$")(3)) Is Nothing) Then
                    ddlStatus.SelectedValue = Session("User_IPORT").ToString().Split("$")(3)
                End If
                Dim clsGet As New ClassFunctionGetData
                Dim ds As DataSet = clsGet.GetRoleUser(txtUsername.Text)
                If (ds.Tables(0).Rows.Count = 1) Then
                    If Not (ddlRole.Items.FindByValue(ds.Tables(0).Rows(0).Item("Role_no")) Is Nothing) Then
                        ddlRole.SelectedValue = ds.Tables(0).Rows(0).Item("Role_no")
                    End If
                    If (ds.Tables(0).Rows(0).Item("Role_no") = "00002") Then
                        rowCustomer.Visible = True
                        txtid.Text = Session("User_IPORT").ToString().Split("$")(5) & "-" & Session("User_IPORT").ToString().Split("$")(6)
                    End If
                End If
                ' Session("RolePopup") = clsGet.GetRoleUser(txtUsername.Text)
                'Else
                '    Session("RolePopup") = CreateDataset()
            End If
            'gridRole.DataSource = Session("RolePopup")
            'gridRole.DataBind()
        End If
    End Sub

    Private Sub btnCancel_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnCancel.Click
        '  Session("RolePopup") = Nothing
        Session("User_IPORT") = Nothing
        ScriptManager.RegisterClientScriptBlock(Me.Page, GetType(String), "myscript", " parent.closeModal();", True)
    End Sub

    Private Function ChkParameter() As Boolean
        If (txtUsername.Text.Trim() = "") Then
            ScriptManager.RegisterClientScriptBlock(Me.Page, GetType(String), "myscript", " alert('กรุณาทำการระบุ Username!!');", True)
            Return False
        End If
        If Not (txtPass1.Text.Trim() = "") And (txtPass2.Text.Trim() = "") Then
            If ((txtPass1.Text.Trim() = "") Or (txtPass2.Text.Trim() = "")) Then
                ScriptManager.RegisterClientScriptBlock(Me.Page, GetType(String), "myscript", "alert('กรุณาทำการระบุ Password!!');", True)
                Return False
            End If
            If (txtPass1.Text.Trim() <> txtPass2.Text.Trim()) Then
                ScriptManager.RegisterClientScriptBlock(Me.Page, GetType(String), "myscript", " alert('รหัสผ่านไม่ถูกต้อง !!');", True)
                Return False
            End If
            If Not Regex.IsMatch(txtPass1.Text.ToLower().Trim, "^[a-zA-Z0-9]*$") Then
                ScriptManager.RegisterClientScriptBlock(Me.Page, GetType(String), "myscript", " alert('รูปแบบ Password ไม่ถูกต้อง !!');", True)
                Return False
            End If
        End If


        If (txtName.Text.Trim() = "") Then
            ScriptManager.RegisterClientScriptBlock(Me.Page, GetType(String), "myscript", " alert('กรุณาทำการระบุชื่อผู้ใช้งาน!!');", True)
            Return False
        End If
        If (txtEmail.Text.Trim() = "") Then
            ScriptManager.RegisterClientScriptBlock(Me.Page, GetType(String), "myscript", " alert('กรุณาทำการระบุ E-mail Address!!');", True)
            Return False
        End If
        Dim reg As New System.Text.RegularExpressions.Regex("^[_a-z0-9-]+(\.[_a-z0-9-]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,3})$")
        Dim Email() As String = txtEmail.Text.Split(";")
        For i As Integer = 0 To Email.Length - 1
            If (Email(i) & "" <> "") Then
                If Not reg.IsMatch(Email(i).ToLower().Trim) Then
                    ScriptManager.RegisterClientScriptBlock(Me.Page, GetType(String), "myscript", " alert('รูปแบบ E-mail ไม่ถูกต้อง!!');", True)
                    Return False
                End If
            End If
        Next

        'Dim ds As DataSet = Session("RolePopup")
        'If (ds.Tables(0).Rows(0).Item("Role_no") & "" = "") Then
        '    ScriptManager.RegisterClientScriptBlock(Me.Page, GetType(String), "myscript", " alert('กรุณาทำการเพิ่มสิทธิ์ !!');", True)
        '    Return False
        'End If
        If (ddlRole.SelectedValue = "0") Then
            ScriptManager.RegisterClientScriptBlock(Me.Page, GetType(String), "myscript", " alert('กรุณาทำการเลือกสิทธิ์ !!');", True)
            Return False
        End If
        If Session("User_IPORT") Is Nothing Then
            Dim clsGet As New ClassFunctionGetData
            Dim ds As DataSet = clsGet.GetUserIPORT(txtUsername.Text, True, "0")
            If Not (ds.Tables(0).Rows.Count = 0) Then
                ScriptManager.RegisterClientScriptBlock(Me.Page, GetType(String), "myscript", " alert('Username นี้มีผู้ใช้งานแล้ว !!');", True)
                Return False
            End If
        End If

        Return True
    End Function

    Private Sub btnSave_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnSave.Click
        If (ChkParameter()) Then
            Dim clsEncrypt As New Class_Encrypt
            Dim ds As DataSet = clsGet.Get_Password(txtUsername.Text.ToLower().Trim())
            If Not (ds.Tables(0).Rows.Count = 0) Then
                If (txtPass1.Text.Trim = "") Then
                    txtPass1.Text = clsEncrypt.Decrypt(ds.Tables(0).Rows(0).Item("Password").ToString())
                End If
            End If
            Dim Pass As String = clsEncrypt.Encrypt(txtPass1.Text.ToLower().Trim())
            Session("User_name") = ""
            Dim User_Create As String = Session("User_name") & Date.Now.ToString("dd MMM yyyy", New CultureInfo("th-TH"))
            Dim conn As New System.Data.SqlClient.SqlConnection(connString)
            Dim clsDB As New ClassDatabase
            Dim clsFc As New ClassFunction
            Dim condition As Boolean = True
            Dim tran As System.Data.SqlClient.SqlTransaction = Nothing
            Dim EventSQL As String = ""
            If Not Session("User_IPORT") Is Nothing Then
                EventSQL = "Edit"
            End If
            Dim Customer As String = ""
            Dim Customer_Name As String = ""
            If (txtid.Text.Trim().Split("-")(0).Trim() <> "") Then
                Customer = txtid.Text.Trim().Split("-")(0)
                Customer_Name = txtid.Text.Trim().Split("-")(1)
            End If
            Application.Lock()
            conn.Open()
            tran = clsDB.BeginTran(conn)
            If (EventSQL = "Edit") Then
                If (clsFc.DeleteUser(txtUsername.Text, conn, tran) < 1) Then
                    condition = False
                End If
            End If
            If (clsFc.InsertUser(EventSQL, txtUsername.Text.ToLower(), Pass, txtName.Text, txtEmail.Text, ddlStatus.SelectedValue, Customer, Customer_Name, conn, tran) > 0) Then
                If Not (clsFc.InsertUserRole("", txtUsername.Text.ToLower(), ddlRole.SelectedValue, User_Create, "", conn, tran) > 0) Then
                    condition = False
                End If
            Else
                condition = False
            End If
            If (condition) Then
                clsDB.CommitTran(tran)
                ' Session("RolePopup") = Nothing
                Session("User_IPORT") = Nothing
                Dim test As String = clsFc.sendmail(txtEmail.Text, "", "iPORT", Mail(), "")
                If (test = "") Then
                    ScriptManager.RegisterClientScriptBlock(Me.Page, GetType(String), "myscript", " parent.closeModal();alert('บันทึกข้อมูลสำเร็จ');", True)
                Else
                    ScriptManager.RegisterClientScriptBlock(Me.Page, GetType(String), "myscript", " parent.closeModal();alert('บันทึกข้อมูลสำเร็จ ไม่สามารถส่ง E-Mail ได้');", True)
                End If

            Else
                clsDB.RollBackTran(tran)
                ScriptManager.RegisterClientScriptBlock(Me.Page, GetType(String), "myscript", " alert('เกิดความผิดพลาดในการบันทึก !!');", True)
            End If
            conn.Close()
            Application.UnLock()
            conn.Dispose()
        End If
    End Sub

    Private Function Mail() As String
        Dim HTML As String = ""
        HTML = "<table width='100%' border='0' cellpadding='2' cellspacing='1'>"

        HTML &= "<tr>"
        HTML &= "<td colspan='2' align='right'><font class='White-Style' style='color:#000000'>รายระเอียดการเข้าใช้งานระบบ iPORT</font>&nbsp;</td>"
        HTML &= "</tr>"

        HTML &= "<tr>"
        HTML &= "<td style='width:220px;' align='right'><font class='White-Style' style='color:#000000'>Username :</font>&nbsp;</td>"
        HTML &= "<td align='left'><font class='White-Style' style='color:#000000'>" & txtUsername.Text & "</font></td>"
        HTML &= "</tr>"
        HTML &= "<tr>"
        HTML &= "<td style='width:220px;' align='right'><font class='White-Style' style='color:#000000'>Password :</font>&nbsp;</td>"
        HTML &= "<td align='left'><font class='White-Style' style='color:#000000'>" & txtPass1.Text & "</font></td>"
        HTML &= "</tr>"
        HTML &= "<tr>"
        HTML &= "<td style='width:220px;' align='right'><font class='White-Style' style='color:#000000'>Name :</font>&nbsp;</td>"
        HTML &= "<td align='left'><font class='White-Style' style='color:#000000'>" & txtName.Text & "</font></td>"
        HTML &= "</tr>"
        HTML &= "<tr>"
        HTML &= "<td style='width:220px;' align='right'><font class='White-Style' style='color:#000000'>Role :</font>&nbsp;</td>"
        HTML &= "<td align='left'><font class='White-Style' style='color:#000000'>" & ddlRole.SelectedItem.Text & "</font></td>"
        HTML &= "</tr>"
        HTML &= "<tr>"
        HTML &= "<td style='width:220px;' align='right'><font class='White-Style' style='color:#000000'>URL :</font>&nbsp;</td>"
        HTML &= "<td align='left'><font class='White-Style' style='color:#000000'>http://iport.irpc.co.th</font></td>"
        HTML &= "</tr>"
        'กำหนดวันเริ่มใช้งาน
        HTML &= "<tr>"
        HTML &= "<td style='width:220px;' align='right'><font class='White-Style' style='color:#000000'>กำหนดวันเริ่มใช้งาน :</font>&nbsp;</td>"
        HTML &= "<td align='left'><font class='White-Style' style='color:#000000'>18 พฤษภาคม 2554</font></td>"
        HTML &= "</tr>"

        HTML &= "<tr>"
        HTML &= "<td style='width:220px;' align='right'><font class='White-Style' style='color:#000000'>สอบถามเพิ่มเติมติดต่อ :</font>&nbsp;</td>"
        HTML &= "<td align='left'><font class='White-Style' style='color:#000000'>port.customerservice@irpc.co.th  เบอร์ต่อ 7811</font></td>"
        HTML &= "</tr>"

        HTML &= "</table>"

        Return HTML
    End Function

    Private Function CreateDataset() As DataSet
        Dim ds As New DataSet
        Dim dt As New DataTable
        Dim dr As DataRow
        ds.Tables.Add(dt)
        dt.Columns.Add("Role_no", GetType(String))
        dt.Columns.Add("Role_name", GetType(String))
        ds.Tables(0).AcceptChanges()
        dr = ds.Tables(0).NewRow
        dr("Role_no") = ""
        dr("Role_name") = ""
        ds.Tables(0).Rows.Add(dr)
        Return ds
    End Function

    'Private Sub gridRole_RowCommand(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewCommandEventArgs) Handles gridRole.RowCommand
    '    Dim Index As Integer = Convert.ToInt32(e.CommandArgument)
    '    If (e.CommandName = "cmddelete") Then
    '        Dim ds As DataSet = Session("RolePopup")
    '        ds.Tables(0).Rows(Index).Delete()
    '        ds.Tables(0).AcceptChanges()
    '        If ds.Tables(0).Rows.Count = 0 Then
    '            ds = CreateDataset()
    '        End If
    '        Session("RolePopup") = ds
    '        gridRole.DataSource = Session("RolePopup")
    '        gridRole.DataBind()
    '        ScriptManager.RegisterClientScriptBlock(Me.Page, GetType(String), "myscript", " alert('ลบข้อมูลเรียบร้อย !!');", True)
    '    End If
    'End Sub

    'Private Sub gridRole_RowDataBound(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewRowEventArgs) Handles gridRole.RowDataBound
    '    If (e.Row.RowType = DataControlRowType.DataRow) Then
    '        If (gridRole.DataKeys(e.Row.RowIndex).Values("Role_no") & "" = "") Then
    '            Dim Img As ImageButton = CType(e.Row.FindControl("imgdelete"), ImageButton)
    '            Img.Visible = False
    '            e.Row.Cells(0).Text = ""
    '        End If
    '    End If
    'End Sub

    'Private Function ChkRoleDuplicate() As Boolean
    '    Dim ds As DataSet = Session("RolePopup")
    '    For Each dr As DataRow In ds.Tables(0).Rows
    '        If (ddlRole.SelectedValue = dr.Item("Role_no").ToString()) Then
    '            Return False 'แสดงว่าเพิ่มไม่ได้ เกิดข้อมูลซ้ำ
    '        End If
    '    Next
    '    Return True
    'End Function

    'Private Sub btnAdd_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnAdd.Click
    '    If (ChkRoleDuplicate()) Then
    '        If (ddlRole.SelectedValue = "0") Then
    '            ScriptManager.RegisterClientScriptBlock(Me.Page, GetType(String), "myscript", " alert('กรุณาทำการเลือกสิทธิ์ !!');", True)
    '        Else
    '            Dim ds As DataSet = Session("RolePopup")
    '            If (ds.Tables(0).Rows(0).Item("Role_no") & "" = "") Then
    '                ds.Tables(0).Rows(0).Item("Role_no") = ddlRole.SelectedValue
    '                ds.Tables(0).Rows(0).Item("Role_name") = ddlRole.SelectedItem.Text
    '            Else
    '                Dim dr As DataRow = ds.Tables(0).NewRow
    '                dr.Item("Role_no") = ddlRole.SelectedValue
    '                dr.Item("Role_name") = ddlRole.SelectedItem.Text
    '                ds.Tables(0).Rows.Add(dr)
    '            End If
    '            ds.Tables(0).AcceptChanges()
    '            Session("RolePopup") = ds
    '            gridRole.DataSource = Session("RolePopup")
    '            gridRole.DataBind()
    '        End If
    '    Else
    '        ScriptManager.RegisterClientScriptBlock(Me.Page, GetType(String), "myscript", " alert('สิทธิ์นี้ได้ทำเพิ่มไว้ก่อนหน้านี้แล้ว !!');", True)
    '    End If
    'End Sub

    Private Sub ddlRole_SelectedIndexChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles ddlRole.SelectedIndexChanged
        If (ddlRole.SelectedValue = "00002") Then
            rowCustomer.Visible = True
        Else
            rowCustomer.Visible = False
        End If
    End Sub

    Private Sub MainPage_PreInit(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.PreInit
        Dim ds As DataSet = Session("UserData")
        If Not (ds Is Nothing) Then
            Page.MasterPageFile = clsGet.GetMaster_Page(ds.Tables(0).Rows(0).Item("User_Name").ToString(), "")
        End If
    End Sub
End Class